class UploadController < ApplicationController
	skip_before_action :verify_authenticity_token, only: [:upload_file, :upload_image, :upload_video]

  FILE_EXT = [".txt", ".pdf", ".doc", '.xlsx', '.md', '.zip', '.doc', '.docx']
	IMAGE_EXT = [".gif", ".jpeg", ".jpg", ".png", ".svg"]
	VIDEO_EXT = [".mp4", ".webm", ".ogg"]

  def upload_file
		if params[:file]
			FileUtils::mkdir_p(Rails.root.join("public/uploads/files"))

			ext = File.extname(params[:file].original_filename)

			file_validation(ext)
			file_name = "#{SecureRandom.urlsafe_base64}#{ext}"
			# path = Rails.root.join("public/uploads/files/", file_name)

			# File.open(path, "wb") {|f| f.write(params[:file].read)}
			# view_file = Rails.root.join("/download_file/", file_name).to_s
			editor_file = EditorFile.create(file: params[:file], file_type: 'file_other', file_name: file_name)
			render :json => {:link => editor_file.file_url}.to_json
		else
			render :text => {:link => nil}.to_json
		end
  end

  def file_validation(ext)
  	raise "Not allowed" unless FILE_EXT.include?(ext)
  end

	def upload_image
		p '=-------image  1234567890-------------'
		if params[:file]
			FileUtils::mkdir_p(Rails.root.join("public/uploads/files"))
			ext = File.extname(params[:file].original_filename)
			image_validation(ext)
			file_name = "#{SecureRandom.urlsafe_base64}#{ext}"
			#path = Rails.root.join("public/uploads/files/", file_name)

			#File.open(path, "wb") {|f| f.write(params[:file].read)}
			# view_file = Rails.root.join("/download_file/", file_name).to_s
			editor_file = EditorFile.create(file: params[:file], file_type: 'image', file_name: file_name)
			render :json => {:link => editor_file.file_url}.to_json
		else
			render :text => {:link => nil}.to_json
		end
	end

	def image_validation(ext)
		raise "Not allowed" unless IMAGE_EXT.include?(ext)
	end

	def upload_video
		if params[:file]
			FileUtils::mkdir_p(Rails.root.join("public/uploads/files"))

			ext = File.extname(params[:file].original_filename)
			video_validation(ext)
			file_name = "#{SecureRandom.urlsafe_base64}#{ext}"
			#path = Rails.root.join("public/uploads/files/", file_name)

			#File.open(path, "wb") {|f| f.write(params[:file].read)}
			#view_file = Rails.root.join("/download_file/", file_name).to_s
			editor_file = EditorFile.create(file: params[:file], file_type: 'video', file_name: file_name)
			render :json => {:link => editor_file.file_url}.to_json
		else
			render :text => {:link => nil}.to_json
		end
	end

	def video_validation(ext)
		raise "Not allowed" unless VIDEO_EXT.include?(ext)
	end

  def access_file
		# http://localhost:3000/public/uploads/files/5LlIDacvkaSxJkxFr06E1Q.jpeg
		if File.exists?(Rails.root.join("public", "uploads", "files", params[:name]))
			send_data File.read(Rails.root.join("public", "uploads", "files", params[:name])), :disposition => "attachment"
		else
			render :nothing => true
		end
  end
end